<template>
  <TableView class="role">
    <template #form>
      <NSpace justify="space-between">
        <NForm
          :show-feedback="false"
          label-placement="left"
          inline
        >
          <NSpace>
            <NSpace>
              <p style="line-height: 34px">文润志愿服务联盟：</p>
              <NSelect
                :options="listOption"
                v-model:value="form.leagueId"
                placeholder="请选择联盟"
                clearable
                style="width: 150px; margin-right: 20px"
                :render-option="renderOption"
              />
            </NSpace>
            <NSpace>
              <span style="line-height: 34px">姓名：</span>
              <NInput
                placeholder="输入姓名"
                v-model:value="form.volunteerName"
                style="width: 150px; margin-right: 20px"
              />
            </NSpace>
            <NSpace>
              <span style="line-height: 34px">服务类型：</span>
              <NSelect
                :options="serviceTypeOption"
                v-model:value="form.serviceTypeCode"
                placeholder="请选择服务类型"
                clearable
                style="width: 150px; margin-right: 20px"
              />
            </NSpace>
            <NSpace>
              <span style="line-height: 34px">签到状态：</span>
              <NSelect
                :options="signFlagOption"
                v-model:value="form.signFlag"
                placeholder="请选择签到状态"
                clearable
                style="width: 150px; margin-right: 20px"
              />
            </NSpace>
            <NSpace>
              <span style="line-height: 34px">签出状态：</span>
              <NSelect
                :options="signOutFlagOption"
                v-model:value="form.signOutFlag"
                placeholder="请选择签出状态"
                clearable
                style="width: 150px; margin-right: 20px"
              />
            </NSpace>
            <NSpace>
              <span style="line-height: 34px">排班日期：</span>
             <NDatePicker input-readonly
                v-model:formatted-value="range"
                value-format="yyyy-MM-dd"
                type="daterange"
                @update:formatted-value="changeDate"
              />
            </NSpace>
            <NFormItem>
              <NButton
                type="primary"
                style="width: 78px;margin-left: 20px;"
                ghost
                @click="queryTableData(true)"
                :loading="tableLoading"
              >
                查询
              </NButton>
              <NButton
                style="width: 78px;margin: 0 15px;"
                @click="reset()"
                ghost
                type="primary"
              >
                重置
              </NButton>
              <NButton
                type="primary"
                style="margin-left: 20px;"
                @click="exportData()"
                :loading="exportLoading"
              >
                导出Excel
              </NButton>
            </NFormItem>
          </NSpace>
        </NForm>
      </NSpace>
    </template>
    <template #table="props">
      <n-data-table
        v-bind="props"
        :data="tableData"
        :columns="columns"
        :loading="tableLoading"
        size="small"
        :bordered="false"
        :rowKey="rowKey"
        :checked-row-keys="dataListSelections"
        @update:checked-row-keys="selectionChangeHandle"
      />
    </template>
    <template #pagination>
      <NPagination
        show-size-picker
        show-quick-jumper
        :page-sizes="paginationReactive.pageSizes"
        :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page"
        :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange"
        @update:page-size="paginationReactive.onUpdatePageSize"
      >
        <template #suffix>页</template>
        <template #prefix>
          <span style="font-size: 14px">共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>
  <NModal :auto-focus="false" v-model:show="modalRemark">
    <VDialogContent
      @close="cancel"
      @submit="confirmRemark"
      title="备注"
    >
      <div style="width: 500rem; height: 300rem; text-align: center; line-height: 100rem">
        <NSpace justify="flex-start">
          <NForm
            ref="formRef"
            require-mark-placement="left"
            label-placement="left"
            :label-width="120"
            :model="formValue"
            label-align="right"
          >
            <NSpace>
              <NFormItem
                label="排班名称:"
                path="volunteerName"
              >
                <NInput
                  placeholder="请输入排班名称"
                  v-model:value="formValue.scheduleName"
                  clearable
                  style="text-align: left;"
                  class="commonWidths"
                  disabled
                />
              </NFormItem>
            </NSpace>
            <NSpace>
              <NFormItem
                label="志愿者姓名:"
                path="volunteerName"
              >
                <NInput
                  placeholder="志愿者姓名"
                  v-model:value="formValue.volunteerName"
                  clearable
                  class="commonWidths"
                  style="text-align: left;"
                  disabled
                />
              </NFormItem>
            </NSpace>
            <NSpace>
              <NFormItem
                label="备注:"
                path="remark"
              >
                <NInput
                  placeholder="请输入备注"
                  v-model:value="formValue.remark"
                  clearable
                  style="text-align: left;"
                  class="commonWidths"
                  type="textarea"
                />
              </NFormItem>
            </NSpace>
          </NForm>
        </NSpace>
      </div>
    </VDialogContent>
  </NModal>
  <NModal :auto-focus="false" v-model:show="modalSign">
    <VDialogContent
      @close="cancel"
      @submit="confirmSign"
      title="补签"
    >
      <div style="width: 500rem; height: 300rem; text-align: center; line-height: 100rem">
        <NSpace justify="center">
          <NForm
            ref="signRef"
            require-mark-placement="left"
            label-placement="left"
            :label-width="120"
            :rules="rules"
            :model="formValue"
            label-align="left"
          >
            <NSpace>
              <NFormItem
                label="志愿者姓名:"
                path="volunteerName"
              >
                <NInput
                  placeholder="请输入标题"
                  v-model:value="formValue.volunteerName"
                  clearable
                  class="commonWidths"
                  style="text-align: left;"
                  disabled
                />
              </NFormItem>
            </NSpace>
            <NSpace>
              <NFormItem
                label="签到时间:"
                path="startSignDate"
                ref="startSignDate"
              >
               <NDatePicker input-readonly
                  class="commonWidths"
                  placeholder="请选择"
                  style="text-align: left;flex: 1"
                  format="yyyy-MM-dd HH:mm:ss"
                  type="datetime"  default-time="00:00:00"
                  v-model:formatted-value="formValue.startSignDate"
                  @update:value="updateStartSignDate"
                  :is-date-disabled="dateDisabled"
                />
              </NFormItem>
            </NSpace>
            <NSpace>
              <NFormItem
                label="签出时间:"
                path="endSignDate"
                ref="endSignDate"
              >
               <NDatePicker input-readonly
                  placeholder="请选择"
                  class="commonWidths"
                  style="text-align: left;flex: 1"
                  format="yyyy-MM-dd HH:mm:ss"
                  type="datetime"  default-time="00:00:00"
                  v-model:formatted-value="formValue.endSignDate"
                  @update:value="updateEndSignDate"
                  :is-date-disabled="dateDisabled"
                />
              </NFormItem>
            </NSpace>
          </NForm>
        </NSpace>
      </div>
    </VDialogContent>
  </NModal>
</template>

<script setup lang="ts">
import {
  useMessage,
  NButton,
  NSpace,
  NDataTable,
  NInput,
  type DataTableColumns,
  NPagination,
  NModal,
  NForm,
  NFormItem,
  NSelect,
  NTag,
  NDatePicker,
  NTooltip,
  FormItemInst
} from 'naive-ui'
import { onActivated, onMounted, reactive, ref, h ,watch} from 'vue'
import { sendRequest } from '@/utils/api'
import type { examineModal } from '@/api/volunteer'
import type { HttpResponse, HttpResponsePagination } from '@/utils/http'
import TableView from '@/components/TableView.vue'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import { useRoute, useRouter } from 'vue-router'
import dayjs from 'dayjs';
import { getToken } from '@/utils/auth'

const message = useMessage()
const router = useRouter()

onActivated(() => {
  if (window.flags.flushRole) {
    queryTableData(true)
    window.flags.flushRole = false
  }
})
const reset = () => {
  resetForm();
  range.value = null
}

const dateDisabledBefore = (ts: any, data: any) => {
  if (data) {
    let time = new Date(data).getTime()
    return ts > time
  }
  return false
}
const dateDisabledAfter = (ts: number, data: any) => {
  let time = new Date(data).getTime()
  return ts < time
}

// table的key选择
const dataListSelections: any = ref([])
function selectionChangeHandle(val: any) {
  dataListSelections.value = val
}

const rowKey: any = (row: any) => row.scheduleRelId || ''
const rowKeys = ref([])
const djIds = ref([])
const range = ref(null)
const tableData = ref<examineModal[]>([])
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    queryTableData()
  }
})
type Reset = () => void
function useQueryForm<T = unknown>(form: T, reset: Reset): [form: T, reset: Reset] {
  return [form, reset]
}
const modalRemark = ref(false)
const modalSign = ref(false)
const route = useRoute()
const title = ref('志愿服务联盟新增');
const [form, resetForm] = useQueryForm(
  reactive({
    leagueId: null,
    startDate: null,
    endDate: null,
    serviceTypeCode: null,
    signFlag: null,
    signOutFlag: null,
    volunteerName: null,
  }),
  () => {
    form.serviceTypeCode = null,
    form.leagueId = null,
    form.startDate = null,
    form.endDate = null,
    form.volunteerName = null,
    form.signFlag = null,
    form.signOutFlag = null
  }
)

let formValue = reactive({
  id: null,
  remark: null,
  endSignDate: null,
  startSignDate: null,
  volunteerName: null,
  scheduleName: null
})

const dateDisabled = (ts: number) => {
  const today = new Date().getTime();
  return today < ts;
}

const  renderOption = ({ node, option }: { node: VNode; option: SelectOption }) =>
  h(NTooltip, null, {
    trigger: () => node,
    default: () => option.label
  })


const changeDate = (v: any) => {
  range.value = v
  form.startDate = v ? `${v[0]} 00:00:00` : null
  form.endDate = v ? `${v[1]} 23:59:59`  : null
}

const startSignDate = ref<FormItemInst | null>(null)
const endSignDate = ref<FormItemInst | null>(null)

const rules = {
  endSignDate: {
    required: true,
    trigger: ['blur', 'change', 'end_date'],
    validator(rule:any, value:any) {
      console.log('endSignDate', value);
      if (!value) {
        return new Error('请选择签出时间')
      }
      else {
        if (formValue.startSignDate) {
          let start = dayjs(`${formValue.startSignDate}`)
          let end = dayjs(`${value}`)
          if (end.diff(start, 'second') < 0) {
            return new Error('签出时间不能早于签到时间')
          } else {
            return true
          }
        } else {
          return true
        }
      }
    }
  },
  startSignDate: {
    required: true,
    trigger: ['blur', 'change', 'start_date'],
    validator(rule:any, value:any) {
      console.log('startSignDate', value);
      if (!value) {
        return new Error('请选择签到时间')
      }
      else {
        if (formValue.endSignDate) {
          let end = dayjs(`${formValue.endSignDate}`)
          let start = dayjs(`${value}`)
          if (end.diff(start, 'second') < 0) {
            return new Error('签出时间不能早于签到时间')
          } else {
            return true
          }
        } else {
          return true
        }
      }
    }
  },
}

const updateStartSignDate = () => {
  if (formValue.startSignDate) {
    setTimeout(()=>{
      startSignDate.value?.validate({ trigger: 'start_date' })
      endSignDate.value?.validate({ trigger: 'end_date' })
    }, 200)
  }
}

const updateEndSignDate = () => {
  if (formValue.endSignDate) {
    setTimeout(()=>{
      startSignDate.value?.validate({ trigger: 'start_date' })
      endSignDate.value?.validate({ trigger: 'end_date' })
    }, 200)
  }
}

const listOption = ref([]);
const signFlagOption = ref([
  {
    label: '待签到',
    value: 0
  },
  {
    label: '正常',
    value: 1
  },
  {
    label: '补签',
    value: 2
  }]);
const signOutFlagOption = ref([
  {
    label: '待签出',
    value: 0
  },
  {
    label: '正常',
    value: 1
  },
  {
    label: '补签',
    value: 2
  }
]);

const serviceTypeOption = ref([])

const columns: DataTableColumns<examineModal> = [
  {
    type: 'selection',
    fixed: 'left',
    width: '2rem'
  },
  {
    title: '文润志愿服务联盟',
    key: 'leagueName',
    width: '10rem',
    align: 'center'
  },
  {
    title: '服务类型',
    key: 'serviceType',
    width: '10rem',
    align: 'center',
  },
  {
    title: '志愿者姓名',
    key: 'volunteerName',
    width: '10rem',
    align: 'center',
  },
  {
    title: '证件号',
    key: 'cardNum',
    width: '10rem',
    align: 'center',
  },
  {
    title: '手机号',
    key: 'mobilePhone',
    width: '10rem',
    align: 'center',
  },
  {
    title: '排班日期',
    key: 'startConfigDate',
    width: '10rem',
    align: 'center',
    render: (row: any) => {
      return (
        h('span', null, [
          h('span', null, dayjs(row.startConfigDate).format('YYYY-MM-DD'))
        ])
      )
    }
  },
  {
    title: '签到时间',
    key: 'startSignDate',
    width: '10rem',
    align: 'center',
  },
  {
    title: '签出时间',
    key: 'endSignDate',
    width: '10rem',
    align: 'center',
  },
  {
    title: '签到状态',
    key: 'signFlag',
    width: '10rem',
    align: 'center',
    render: (row: any) => {
      let name = '';
      switch (row.signFlag) {
        case 0:
          name = '待签到'
          break;
        case 1:
          name = '正常'
          break;
        case 2:
          name = '补签'
          break;
        case 3:
          name = '迟到'
          break;
        case 4:
          name = '正常'
          break;
        default:
          name = '待签到'
          break;
      }
      return h(
        NTag,
        {
          style: {
            marginRight: '6px'
          },
          type: 'info',
          bordered: false
        },
        {
          default: () => name
        }
      )
    }
  },
  {
    title: '签出状态',
    key: 'signOutFlag',
    width: '10rem',
    align: 'center',
    render: (row: any) => {
      let name = '';
      switch (row.signOutFlag) {
        case 0:
          name = '待签出'
          break;
        case 1:
          name = '正常'
          break;
        case 2:
          name = '补签'
          break;
        case 3:
          name = '正常'
          break;
        case 4:
          name = '早退'
          break;
        default:
          name = '待签到'
          break;
      }
      return h(
        NTag,
        {
          style: {
            marginRight: '6px'
          },
          type: 'info',
          bordered: false
        },
        {
          default: () => name
        }
      )
    }
  },
  {
    title: '操作',
    key: 'action',
    width: '20rem',
    align: 'center',
    fixed: 'right',
    render: (row: any) => {
      let name = '';
      row.listFlag == 1 ? name = '下架' : name = '上架'
      return [
        h(
          NButton,
          {
            type: 'primary',
            quaternary: true,
            onClick: () => handleSign(row)
          },
          {
            default: () => '补签'
          }
        ),
        h(
          NButton,
          {
            type: 'error',
            quaternary: true,
            onClick: () => handleNote(row)
          },
          {
            default: () => '备注'
          }
        )
      ]
    }
  }
]
const tableLoading = ref(false)
const queryTableData = async (resetPage = false) => {
  if (resetPage) paginationReactive.page = 1
  tableLoading.value = true
  let params:any = {
    serviceTypeCode: form.serviceTypeCode,
    signFlag: form.signFlag,
    signOutFlag: form.signOutFlag,
    volunteerName: form.volunteerName,
    leagueId: form.leagueId,
    page: paginationReactive.page,
    limit: paginationReactive.pageSize,
    startDate: form.startDate,
    endDate: form.endDate,
  }
  const [error, res] = await sendRequest<HttpResponsePagination<examineModal>>({
    module: 'volunteer',
    api: 'attendanceRecordList',
    override: {
      params: params
    }
  })
  tableLoading.value = false
  if (error) return message.error(error.message)
  paginationReactive.itemCount = res.data.totalCount
  res.data.list = res.data.list.map((item:any) => {
    item.defalutId = `${item.scheduleId}-${item.volunteerId}`;
    return item;
  })
  tableData.value = res.data.list
}

const exportLoading = ref(false)
const exportData = async() => {
  let scheduleId:any = [];
  let scheduleIds:srting = '';
  let volunteerId:any = [];
  let volunteerIds:srting = '';
  tableData.value.forEach((item:any)=>{
    if (dataListSelections.value.indexOf(item.scheduleRelId) != -1) {
      scheduleId.push(item.scheduleRelId)
      volunteerId.push(item.volunteerId)
    }
  })
  scheduleIds = scheduleId.join(',');
  volunteerIds = volunteerId.join(',');
  exportLoading.value = true
  const [error, res, headers] = await sendRequest<HttpResponse>({
    module: 'volunteer',
    api: 'attendanceRecordExport',
    override: {
      params: {
        scheduleRelIds: scheduleIds,
        // volunteerIds,
        serviceTypeCode: form.serviceTypeCode,
        signFlag: form.signFlag,
        signOutFlag: form.signOutFlag,
        volunteerName: form.volunteerName,
        leagueId: form.leagueId,
        page: paginationReactive.page,
        startDate: form.startDate,
        endDate: form.endDate,
        limit: 99999
      }
    }
  })
  if (error) return message.error(error.message), (exportLoading.value = false)
  download(headers, res, '志愿者考勤记录')
  exportLoading.value = false
  message.success('导出成功')
}
function download(headers: any, data: any, name?: string) {
  const val = headers['content-disposition']?.match(/(?<=filename=)(.*)/)
  let filename = val ? decodeURIComponent(val[0]) : name + '导出.xlsx'
  if (!filename.includes('xlsx')) {
    filename = filename.replace('xls', 'xlsx')
  }
  const a = document.createElement('a')
  let binaryData = []
  binaryData.push(data)
  a.href = window.URL.createObjectURL(new Blob(binaryData))
  a.download = filename
  a.click()
  window.URL.revokeObjectURL(a.href)
}

//下拉
const getFunction = async () => {
  listOption.value = []
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'volunteer',
    api: 'leagueOptions'
  })
  if (error) return message.error(error.message)
  res.data.forEach((i: any) => {
    // @ts-ignore
    listOption.value.push({ label: i.label, value: i.value })
  })
}

//下拉
const getServiceFunction = async () => {
  serviceTypeOption.value = []
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'clue',
    api: 'listByParentCode',
    override: {
      params: {
        dicCode: 'A56'
      }
    }
  })
  if (error) return message.error(error.message)
  res.data.forEach((i: any) => {
    // @ts-ignore
    serviceTypeOption.value.push({ label: i.dicName, value: i.dicCode })
  })
}

const handleSign = (obj:any) => {
  // formValue = obj;
  Object.assign(formValue, obj);
  console.log('formValue', formValue)
  modalSign.value = true;
}

const handleNote = (obj:any) => {
  // formValue = obj;
  Object.assign(formValue, obj);
  console.log('formValue', formValue)
  modalRemark.value = true;
}

onMounted(() => {
  getFunction()
  getServiceFunction()
  queryTableData(true)
})

const confirmRemark = async() => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'volunteer',
    api: 'attendanceRecordUpdate',
    override: {
      data: formValue
    }
  })
  if (error) return message.error(error.message)
  message.success('备注成功');
  queryTableData(true)
  cancel()
}

const signRef = ref<FormInst | null>(null)
const confirmSign = () => {
  signRef.value?.validate(async (error) => {
    if (error) return
    try {
      const [error, res] = await sendRequest<HttpResponse>({
        module: 'volunteer',
        api: 'attendanceRecordRepairSign',
        override: {
          data: formValue
        }
      })
      if (error) return message.error(error.message)
      message.success('补签成功');
      queryTableData(true)
      cancel()
    } catch (error: any) {
      message.error(error.message)
    }
  })
}

const cancel = () => {
  formValue.id = null;
  formValue.remark = null;
  formValue.endSignDate = null;
  formValue.startSignDate = null;
  formValue.volunteerName = null;
  modalSign.value = false;
  modalRemark.value = false;
}
watch(
  () => route,
  () => {
    if (
      route.path == '/collectionManagement/collectionProcess/clueManagement/index'
    ) {
      queryTableData(true)
    }
  },
  { deep: true, immediate: true }
)
</script>
<style>

.n-form-item .n-form-item-feedback-wrapper .n-form-item-feedback.n-form-item-feedback--error {
  text-align: left !important;
}
</style>
<style lang="scss" scoped>
.role {
  padding: 29rem 20rem 42rem 30rem;
  color: rgba(0, 0, 0, 0.85);
}
.commonWidths {
  width: 300px;
}
</style>
